﻿/*
* Copyright (c) 2010-2012 Tesla Engine Group
* 
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* 
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* 
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/

using System;
using System.Collections.Generic;
using System.IO;
using Tesla.Graphics;

namespace Tesla.Content.Loaders {
    /// <summary>
    /// Binary external writer specifically for texture files. The writer tries to minimize duplicate resources by tracking
    /// textures directly.
    /// </summary>
    public sealed class TextureBinaryExternalWriter : ExternalWriter<Texture> {
        private Dictionary<Texture, String> _textures;
        private int _count;

        /// <summary>
        /// Initializes a new instance of the <see cref="TextureBinaryExternalWriter"/> class.
        /// </summary>
        public TextureBinaryExternalWriter()
            : base("texture", String.Empty) {
                _textures = new Dictionary<Texture, string>();
                _count = 0;
        }

        /// <summary>
        /// Called when the writer is initialized by the savable writer, when it is registered with the savable
        /// writer.
        /// </summary>
        protected override void OnInitialize() {
            _textures.Clear();
            _count = 0;
        }

        /// <summary>
        /// Writes the specified name.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <param name="value">The value.</param>
        /// <returns></returns>
        public override ExternalReference Write(String name, Texture value) {
            String filePath;

            if(_textures.TryGetValue(value, out filePath)) {
                return new ExternalReference(filePath);
            }

            String fileDir = GetFileDirectory();
            String resourceName = GetPrimaryResourceName();
            if(!Directory.Exists(fileDir)) {
                Directory.CreateDirectory(fileDir);
            }

            String extName = value.Name;

            if(extName == null) {
                if(_count > 0) {
                    extName = String.Format("{0}_{1}_{2}", resourceName, DefaultOutputName, _count);
                } else {
                    extName = String.Format("{0}_{1}", resourceName, DefaultOutputName);
                }
            }

            filePath = Path.Combine(fileDir, extName);
            filePath = Path.ChangeExtension(filePath, ".tebo");

            //If we're not overwriting, try and come up with a unique file name several times before giving up
            if(!Overwrite) {
                int count = 0;
                while(File.Exists(filePath)) {
                    filePath = Path.Combine(fileDir, String.Format("{0}-{1}", extName, count));
                    filePath = Path.ChangeExtension(filePath, ".tebo");
                    if(count > 5) {
                        break;
                    }
                    count++;
                }
            }

            //Write to the file
            BinaryExporter exporter = new BinaryExporter();
            exporter.Save(value, filePath);

            String relName;

            if(String.IsNullOrEmpty(OutputDirectory)) {
                relName = Path.GetFileName(filePath);
            } else {
                relName = Path.Combine(OutputDirectory, Path.GetFileName(filePath));
            }

            _textures.Add(value, relName);
            _count++;
            return new ExternalReference(relName);
        }

        /// <summary>
        /// Cleans up any remaining resources and finishes writing external objects.
        /// </summary>
        public override void Flush() {
            _textures.Clear();
            _count = 0;
        }
    }
}
